<?php
//dezend by http://www.yunlu99.com/ QQ:270656184
function sms($uid, $pwd, $mobile, $content)
{
	$res = sendSMS_cms($uid, $pwd, $mobile, $content);

	if ($res['stat'] == '100') {
		return true;
	}
	else {
		return false;
	}
}

function sendSMS_cms($uid, $pwd, $mobile, $content, $template = '')
{
	$apiUrl = 'http://api.sms.cn/sms/';
	$data = array('ac' => 'send', 'uid' => $uid, 'pwd' => md5($pwd . $uid), 'mobile' => $mobile, 'content' => $content, 'template' => $template, 'format' => 'json');
	$result = postSMS_cms($apiUrl, $data);
	$re = json_to_array($result);
	return $re;
}

function postSMS_cms($url, $data = '')
{
	$row = parse_url($url);
	$host = $row['host'];
	$port = '';
	$port = (isset($row['port']) && $row['port'] ? $row['port'] : 80);
	$file = $row['path'];
	$post = '';

	while (list($k, $v) = each($data)) {
		$post .= rawurlencode($k) . '=' . rawurlencode($v) . '&';
	}

	$post = substr($post, 0, -1);
	$len = strlen($post);
	$fp = @fsockopen($host, $port, $errno, $errstr, 10);

	if (!$fp) {
		return $errstr . ' (' . $errno . ")\n";
	}
	else {
		$receive = '';
		$out = 'POST ' . $file . " HTTP/1.1\r\n";
		$out .= 'Host: ' . $host . "\r\n";
		$out .= "Content-type: application/x-www-form-urlencoded\r\n";
		$out .= "Connection: Close\r\n";
		$out .= 'Content-Length: ' . $len . "\r\n\r\n";
		$out .= $post;
		fwrite($fp, $out);

		while (!feof($fp)) {
			$receive .= fgets($fp, 128);
		}

		fclose($fp);
		$receive = explode("\r\n\r\n", $receive);
		unset($receive[0]);
		return implode('', $receive);
	}
}

defined('BASEPATH') || exit('No direct script access allowed');

if (!function_exists('send_mobile')) {
	function send_mobile($uid, $pwd, $mobile, $content)
	{
		return sms($uid, $pwd, $mobile, $content);
	}
}

if (!function_exists('json_to_array')) {
	function json_to_array($p)
	{
		if (mb_detect_encoding($p, array('ASCII', 'UTF-8', 'GB2312', 'GBK')) != 'UTF-8') {
			$p = iconv('GBK', 'UTF-8', $p);
		}

		return json_decode($p, true);
	}
}

?>
